package com.ywwl.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ywwl.dao.RoleMapper;
import com.ywwl.domain.table.SysRole;
import com.ywwl.service.RoleService;
import com.ywwl.util.response.ResponseMsg;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Service("RoleService")
public class RoleServiceImpl implements RoleService {


    @Resource
    private RoleMapper roleMapper;


    @Override
    public List<SysRole> list() throws Exception {
        return roleMapper.list(null, null);
    }

    @Override
    public PageInfo<SysRole> listByPage(HashMap<String, String> whereMap, int pageIndex, int pageSize, HashMap<String, String> orderMap) throws Exception {
        PageHelper.startPage(pageIndex, pageSize);

        return new PageInfo(roleMapper.list(whereMap, orderMap));
    }

    @Override
    public SysRole selectByPrimaryKey(int id) throws Exception {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public SysRole selectByWhere(HashMap<String, String> hashMap) throws Exception {
        return roleMapper.selectByWhere(hashMap);
    }

    @Override
    public ResponseMsg insert(SysRole role) throws Exception {
        ResponseMsg msg = new ResponseMsg();

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("roleName", role.getRoleName());

        SysRole model = roleMapper.selectByWhere(hashMap);
        if (model != null) {
            msg.setCode(-1);
            msg.setMessage("该角色已存在！");

            return msg;
        }

        if (roleMapper.insert(role)) {
            msg.setMessage("角色添加成功！");
        } else {
            msg.setCode(-1);
            msg.setMessage("角色添加失败！");
        }

        return msg;
    }

    @Override
    public ResponseMsg update(SysRole role) throws Exception {
        ResponseMsg msg = new ResponseMsg();

        SysRole model = roleMapper.selectByPrimaryKey(role.getId());
        if (model == null) {
            msg.setCode(-1);
            msg.setMessage("该角色不存在！");

            return msg;
        }

        if (roleMapper.update(role)) {
            msg.setMessage("角色修改成功！");
        } else {
            msg.setCode(-1);
            msg.setMessage("角色修改失败！");
        }

        return msg;
    }

    @Override
    public ResponseMsg delete(int id) throws Exception {
        ResponseMsg msg = new ResponseMsg();

        SysRole role = roleMapper.selectByPrimaryKey(id);
        if (role == null) {
            msg.setCode(-1);
            msg.setMessage("该角色不存在！");
        }

        if (roleMapper.delete(id)) {
            msg.setMessage("角色删除成功！");
        } else {
            msg.setCode(-1);
            msg.setMessage("角色删除失败！");
        }

        return msg;
    }
}
